package com.klun.project.common.constans;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Resource {
	
	private int num = 0 ;
	private final static int maxValue = 10;
	private final static int minValue = 0 ;
	private Lock lock = new ReentrantLock();
	private Condition condition = lock.newCondition();
	
	public void put() throws InterruptedException {  //生产
		try {
			lock.lock();
			if(num == maxValue) {
				condition.await();
			}else {
				Thread.sleep(1000);
				num++;
				System.out.println(Thread.currentThread().getName() + " 生产1个，剩余" + num + "个");
				condition.signalAll();
			}
		}finally {
			lock.unlock();
		}
	}
	
	public void get() throws InterruptedException { //消费
		try {
			lock.lock();
			if(num == minValue) {
				condition.await();
			}else {
				Thread.sleep(1000);
				num--;
				System.out.println(Thread.currentThread().getName() + " 消费1个，剩余" + num + "个");
				condition.signalAll();
			}
		}finally {
			lock.unlock();
		}
	}
}
